<template>
  <div class="order">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" @keyup.enter.native="getDataList()">
      <el-form-item label="订单状态">
        <el-select v-model="formInline.status" placeholder="查看订单" clearable>
          <el-option label="未发货" :value="1" />
          <el-option label="已发货" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker
          v-model="formInline.date"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择一个时间"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getDataList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table border
              :data="dataList"
              v-loading="dataListLoading"
              @selection-change="selectionChangeHandle"
              style="width: 100%">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column prop="orderCode"
                       label="订单编号"
                       header-align="center"
                       align="center"
                       width="150" />
      <el-table-column prop="receiver"
                       label="收货人"
                       header-align="center"
                       align="center"
                       width="100" />
      <el-table-column prop="receiverPhone"
                       label="收货人电话"
                       header-align="center"
                       align="center"
                       width="190"
                       />
      <el-table-column label="收货人地址"
                       header-align="center"
                       align="center"
                       width="240"
                       >
        <template slot-scope="scope">
          {{ scope.row.address }}   {{ scope.row.fullAddress }}
        </template>
      </el-table-column>
      <el-table-column prop="remark"
                       label="备注"
                       header-align="center"
                       align="center"
                       width="240"/>
      <el-table-column prop="sendTime"
                       label="最晚发货时间"
                       header-align="center"
                       align="center"
                       width="180" />
      <el-table-column
                        fixed="right"
                        header-align="center"
                        align="center"
                        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="getInfoHandler(scope.row.orderCode)">查看详情</el-button>
          <el-button type="text" size="small" @click="send(scope.row.orderStatus,scope.row.orderCode)">
            <span v-if="scope.row.orderStatus===1">未发货</span>
            <span v-else-if="scope.row.orderStatus===2">已发货</span>
          </el-button>
<!--          <el-button type="text" size="small" @click="cancle(scope.row.orderCode)">
            <span v-if="scope.row.orderStatus==2">取消发货</span>
          </el-button>-->
        </template>
<!--<div v-for="(item, index) in dataForm.skuNumber" :key="index" class="step-item">
      <div >
        商品名称: {{ item.orderInfo.spuName }}
      </div>
      <div >
        商品数量: {{ item.num }}
      </div>
      <div >
        商品规格: {{ item.orderInfo.skuSpecs }}
      </div>
    </div>-->
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
<!--    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
                   :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>-->
  <get-info v-if="getInfoVisible" ref="getInfo" ></get-info>
  </div>
</template>

<script>
import GetInfo from './get-info'
export default {
  data(){
    return{
      formInline:{
        date:'',
        status: ''
      },
      sendFoodsTime:'',
      sendMessage:'',
      dataList: [],
      dataList2:[],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      getInfoVisible: false,
      username:'',
      token:'',
      webSocketObject:null,
      userId:0,
      flag:0,
    }
  },
  components:{
    GetInfo
  },
  activated() {
    this.getDataList()
    this.getUserId()
    this.getDataListAll()

  },
  created() {
    //初始化WebSocket
    this.webSocketInit()
  },
  methods:{
    //获取所有数据
    getDataListAll(){
      this.$http({
        url: this.$http.adornUrl('/MerchantOrder/All'),
        method: 'get',
        params: this.$http.adornParams({})
      }).then(({data}) => {
        if (data && data.code === 0) {
          console.log(data)
          this.dataList2 = data.list
        } else {
          this.dataList2 = []
        }

    })},
    //获取数据列表
    getDataList() {
      this.dataListLoading = true
      console.log(this.formInline.date)
        this.$http({
          url: this.$http.adornUrl('/MerchantOrder/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'date':this.formInline.date,
            'status':this.formInline.status
          })
        }).then(({data}) => {
          if (data && data.code===0){
            this.dataList=data.list.list
            this.totalPage=data.list.totalCount
          }else{
            this.dataList=[]
            this.totalPage=0
          }
          this.dataListLoading = false
        })
      /*else if (this.formInline.status === '' && this.formInline.date !== ''){
        this.$http({
          url: this.$http.adornUrl('/MerchantOrder/MerchantOrderStatus'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'date': this.formInline.date
          })
        }).then(({data}) => {
          console.log(data)
          if (data && data.code === 0) {
            this.dataList = data.list.list
            this.totalPage = data.list.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      }else{
        this.$http({
          url: this.$http.adornUrl('/MerchantOrder/MerchantOrderStatus'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'status': this.formInline.status,
            'date': this.formInline.date
          })
        }).then(({data})=>{
          if (data&&data.code===0){
            this.dataList = data.list.list
            this.totalPage = data.list.totalCount
          }else{
            this.dataList=[]
            this.totalPage=0
          }
          this.dataListLoading=false
        })
      }*/
    },
    //多选
    selectionChangeHandle(val){
      this.dataListSelections=val
    },
    webSocketInit(){
      const userid=this.userId
      console.log(userid)
      const webSocketUrl = 'ws://localhost:8090/dishes/websocket/'+userid
      this.webSocketObject = new WebSocket(webSocketUrl) // 在连接中添加token信息
      this.webSocketObject.onopen = this.webSocketOnOpen
      this.webSocketObject.onmessage = this.webSocketOnMessage
      this.webSocketObject.onerror = this.webSocketOnError
      this.webSocketObject.onclose = this.webSocketOnClose
    }
    ,
    webSocketOnOpen(e){
      console.log('与服务端连接打开->',e)
    },
    webSocketOnMessage(e){
      console.log(e.data)
      /*if (e!=null) {
        this.flag++;
        this.getDataList()
        console.log("211111111->", e)
      }*/
      this.getDataListAll();//有机会试试将这个代码放到最后这样就能达到每次都是旧的数据
      let formattedMessage = e.data;
      let receiveMessage = JSON.parse(formattedMessage);
      let jsonArray = receiveMessage.map(jsonStr => JSON.parse(jsonStr));
      const currentViewPage = this.pageIndex || 1;
      const itemsPerPage = this.pageSize;
      // 计算当前页的起始和结束索引
      const currentPageStartIndex = (currentViewPage - 1) * itemsPerPage;
      const currentPageEndIndex = currentPageStartIndex + itemsPerPage;
      let isCurrentPageFull = this.dataList.length >= itemsPerPage;
      console.log(this.dataList2.length)
      jsonArray.forEach(newOrder => {
        // 检查新数据是否已存在且当前页面是否有空间
        const existingOrder = this.dataList2.find(order => order.orderCode === newOrder.orderCode);

        /*if (!existingOrder && !isCurrentPageFull) {
          this.dataList.push(newOrder);
          this.totalPage=this.dataList2.length+1
          // 更新当前页面是否已满的状态
          isCurrentPageFull = this.dataList.length === currentPageEndIndex;
        }*/
        if(!existingOrder){
          if (!isCurrentPageFull){
            this.dataList.push(newOrder);
            this.totalPage=this.dataList2.length+1
            // 更新当前页面是否已满的状态
           /* isCurrentPageFull = this.dataList.length === currentPageEndIndex;*/
          }else {
            this.totalPage=this.dataList2.length+1
          }
        }
      });
    },
    webSocketOnError(e){
      console.log('与服务端连接异常->',e)
    },
    webSocketOnClose(e){
      console.log('与服务端连接关闭->',e)
    },
    handleSendButton() {
      const userid = this.userId
      console.log(this.userId)
      /*const userId = this.userId*/
      const message = this.sendMessage
      this.webSocketObject.send(JSON.stringify({
        id: 1,
        message,
        time: new Date().getTime()
      }))
      this.sendMessage = ''
    },
   /* handleLogoutButton(){
      removeUsername() //清除username然后断开连接
      this.webSocketObject.close();
      this.$router.push({
        name: 'Login'
      })
    }*/
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    getUserId(){
      this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/sys/user/info'),
          method: 'get',
          params: this.$http.adornParams({})
        }).then(({data}) => {
          if (data && data.code===0){
            this.userId=data.user.userId
            this.webSocketInit()
          }else{
            this.dataList=[]
            this.totalPage=0
          }
          this.dataListLoading = false
        })
    },
    send(orderStatus,orderCode){
      if(orderStatus===1){//未发货
        var orderCo=orderCode
        this.$confirm('确认发货吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/MerchantOrder/send'),
            method: 'get',
            params: this.$http.adornParams({
              'orderCode': orderCode
            })
          }).then(({data}) => {
            if (data && data.code===0){
              this.$message({
                message:'操作成功',
                type:'success',
                duration:1500,
                onClose:()=>{
                  this.getDataList()
                }
              })
            }else{
              this.$message.error(data.msg)
              }
            })
          }).catch(()=>{})
        }else {
        this.$confirm('你已发货，不能重复发货', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        })
      }
      },
    getInfoHandler(orderCode){
      this.getInfoVisible=true
      this.$nextTick(() => {
        this.$refs.getInfo.init(orderCode)
      })
    }
    }
}


</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
